package com.markyao.service.impl;

import com.markyao.dao.mapper.MiaoshaMapper;
import com.markyao.dao.pojo.MiaoshaOrder;
import com.markyao.dao.pojo.User;
import com.markyao.miaosha.Const;
import com.markyao.miaosha.SeckillKey;
import com.markyao.service.MiaoshaService;
import com.markyao.service.OrderService;
import com.markyao.service.ProductService;
import com.markyao.service.RedisService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MiaoshaServiceImpl implements MiaoshaService {
    private static final String  md5ForPath="123qaz@key!";
    @Autowired
    RedisService redisService;
    @Autowired
    MiaoshaMapper miaoshaMapper;
    @Autowired
    ProductService productService;
    @Autowired
    OrderService orderService;

    @Override
    public String createMiaoshaPath(User user, long goodsId) {
        //通过md5生成秒杀路径path
        if (user==null || goodsId<=0){
            return null;
        }
        String path=DigestUtils.md5Hex(user.getUid()+""+goodsId+""+md5ForPath);
        //以SeckillKey.getSeckillPath+user.getUid()+"-"+goodsId 为key
        //以path为值存入redis
        redisService.set(
                SeckillKey.getSeckillPath,
                user.getUid()+"-"+goodsId,
                path,
                Const.RedisCacheExtime.GOODS_ID);
        return path;
    }

    @Override
    public boolean checkPath(User user, long goodsId, String path) {
        String realPath=redisService.getPath(SeckillKey.getSeckillPath,user.getUid(),goodsId);

        return path.equals(realPath);
    }

    @Override
    public MiaoshaOrder findOrderByUidAndGoodId(Integer uid, Integer goodsId) {
        return miaoshaMapper.findByUidAndGoodId(uid,goodsId);
    }

    @Transactional  //开启事务
    @Override
    public void insertMiaoshaOrder(User user, Integer goodsId) {
        int cnt=productService.reduceMiaoshaCnt(goodsId);//秒杀库存量减1
        if (cnt==1){
            //说明此时数据库中库存量大于等于0，秒杀成功了,生成对应订单-->order与orderItem表
            orderService.addMiaoshaOrder(user.getUid(),goodsId);
            //插入秒杀订单表
            miaoshaMapper.insert(user.getUid(),goodsId);
        }
    }
}
